import numpy as np
import pandas as pd
from collections import Counter

# 读取Iris数据集
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"
data = pd.read_csv(url, header=None)
data.columns = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'class']

# 数据预处理
X = data.iloc[:, :-1].values  # 特征
y = data.iloc[:, -1].values   # 类别标签

# KNN分类函数
def knn(X_train, y_train, X_test, k):
    predictions = []
    for test_point in X_test:
        # 计算测试点与训练点之间的距离（欧氏距离）
        distances = np.linalg.norm(X_train - test_point, axis=1)
        # 选择k个最近邻
        k_nearest_neighbors = np.argsort(distances)[:k]
        # 统计最近邻的类别
        nearest_classes = y_train[k_nearest_neighbors]
        most_common = Counter(nearest_classes).most_common(1)
        predictions.append(most_common[0][0])
    return predictions

# 将数据集分为训练集和测试集
train_size = int(0.8 * len(X))
X_train, X_test = X[:train_size], X[train_size:]
y_train, y_test = y[:train_size], y[train_size:]

# 设置K值
k = 3
predictions = knn(X_train, y_train, X_test, k)

# 评估KNN分类器的准确性
accuracy = np.sum(predictions == y_test) / len(y_test)
print(f"KNN算法分类准确率: {accuracy}")
